from flask import Blueprint, render_template, request, jsonify, flash, redirect, url_for
from app.models import BilingualContent, News, Contact, db
from datetime import datetime

front = Blueprint('front', __name__)

@front.route('/')
def index():
    lang = request.args.get('lang', 'zh')  # 获取语言参数，默认为中文
    slides = BilingualContent.query.filter_by(category='home_slider').all()
    return render_template('front/index.html', 
                         slides=slides,
                         lang=lang)

@front.route('/news')
def news():
    lang = request.args.get('lang', 'zh')  # 默认使用繁体中文
    # 这里暂时不需要从数据库获取数据
    return render_template('front/news.html', lang=lang)

@front.route('/services')
def services():
    lang = request.args.get('lang', 'zh')  # 默认使用繁体中文
    return render_template('front/services.html', lang=lang)

@front.route('/cases')
def cases():
    lang = request.args.get('lang', 'zh')  # 默认使用繁体中文
    return render_template('front/cases.html', lang=lang)

@front.route('/about')
def about():
    lang = request.args.get('lang', 'zh')
    return render_template('front/about.html', lang=lang)

@front.route('/contact', methods=['GET', 'POST'])
def contact():
    # GET 请求直接渲染模板
    if request.method == 'GET':
        return render_template('front/contact.html')
    
    # POST 请求处理表单提交
    if request.method == 'POST':
        try:
            contact = Contact(
                name=request.form.get('name'),
                phone=request.form.get('phone'),
                email=request.form.get('email'),
                message=request.form.get('message'),
                status='pending',
                created_at=datetime.utcnow()
            )
            db.session.add(contact)
            db.session.commit()
            flash('感謝您的諮詢，我們會盡快與您聯繫！', 'success')
            return redirect(url_for('front.contact'))
        except Exception as e:
            flash('提交失敗，請稍後重試。', 'error')
            return redirect(url_for('front.contact')) 